package com.example.server.web.controller;

import com.example.server.web.domain.RespBean;
import com.example.server.web.utils.CodeUtil;
import com.example.server.web.utils.EncryptUtil;
import com.example.server.web.utils.UUIDKeyGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags="公共接口")
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 返回验证码图片
     * @throws ServletException
     * @throws IOException
     */
    @ApiOperation("返回验证码图片")
    @GetMapping(value = "captcha/get-one")
    public RespBean getCode(HttpSession session, HttpServletResponse response) throws IOException {
        //1.获取图片并处理
        BufferedImage image = CodeUtil.getImage();
        Graphics g = image.getGraphics();

        //2.图片内写上数字
        String random = CodeUtil.drawRandomNum((Graphics2D) g);

        //3.将随机数存在session中
        session.setAttribute("captcha", random);

        //4.将验证码图片返回
        //ServletOutputStream out = response.getOutputStream();
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpg", os);
        //IOUtils.closeQuietly(out);

        //5.获取uuid，当作验证码的key
        String uuid = UUIDKeyGenerator.generate("captcha-");

        //6.存进redis中
        redisTemplate.opsForValue().set(uuid,random,2, TimeUnit.MINUTES);

        //7.创建一个map存返回结果
        Map<String, String> map = new HashMap<>();
        map.put("img","data:image/gif;base64,"+EncryptUtil.encodeBase64(os.toByteArray()));
        map.put("uuid",uuid);
        return RespBean.success("data", map);
    }

}
